import { addDialog } from '@/components/SpDialog/index'
import ExportExcelModal from './index.vue'
import type { ExportExcelFormState, ExportExcelOption } from './exportExcelOption'
import type { FormExpose } from 'ant-design-vue/es/form/Form'
import { message } from 'ant-design-vue'
import type { ExportExcelParams } from './model'

export const exportExcel = (
  option: ExportExcelOption,
  request: (data: ExportExcelParams<any>) => Promise<any>
) => {
  const formRef = ref()
  addDialog({
    title: '导出Excel',
    width: '50%',
    contentRenderer: () => h(ExportExcelModal, { ref: formRef, option }),
    beforeSure: function (done) {
      const form = formRef.value.getRef() as FormExpose
      form.validate().then((res) => {
        const currentData = res as ExportExcelFormState
        if (currentData.where === 'select') {
          if (option.selectedRowKeys?.length == 0) {
            message.error('请选择要导出的数据')
            return
          }
        }
        // 移除操作列
        option.columns = option.columns?.filter((item) => item.dataIndex !== 'operation')
        // 拼接请求参数
        let params: ExportExcelParams<any> = {
          where: currentData.where,
          columns: option.columns as ExportExcelParams<any>['columns'],
          selectedRowKeys: option.selectedRowKeys as number[]
        }
        // 查询条件
        if (currentData.where === 'query') {
          params.queryParams = option.queryParams
        }
        // 开启loading
        formRef.value.setLoading(true)
        // 发送请求
        request(params).then((res) => {
          // 判断是否是文件流
          if (res.type == 'application/json') {
            //将 blob转成json
            const reader = new FileReader()
            reader.readAsText(res)
            reader.onload = async function () {
              const result = JSON.parse(reader.result as string)
              if (result.code !== 200) {
                message.error(result.msg)
              }
            }
          } else {
            // 下载文件
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(new Blob([res]))
            link.download = `${currentData.fileName}.xlsx`
            // 模拟点击下载
            link.click()
            window.URL.revokeObjectURL(link.href)
            // 关闭loading
            formRef.value.setLoading(false)
            done()
            message.success('导出成功')
          }
        })
      })
    }
  })
}
